﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

namespace pcsse.MasterPages
{
    public partial class WebForm4 : System.Web.UI.Page
    {
        protected DataTable dt;
        private string id;
        static private int mode;
        static private int attachmentToDel_id;
        static private bool Bf_Delfile;
        static private news_data nd;
        static string file_name;
        static string file_path;
        //private int category_num = 1;
        private void Data_Bind()//绑定下拉列表的数据绑定
        {
            category_DDL_Bind();
            permission_DDL_Bind();
        }
        private void category_DDL_Bind()
        {
            dt = db_news.getDBhandle().GetDataTableBySQL("SELECT * FROM T_CATEGORY");
            DropDownList1.DataSource = dt.DefaultView;
            DropDownList1.DataTextField = "CATEGORY_TITLE";
            DropDownList1.DataValueField = "CATEGORY_ID";
            DropDownList1.DataBind();
        }
        private void permission_DDL_Bind()
        {
            dt = db_news.getDBhandle().GetDataTableBySQL("SELECT * FROM T_PRIORITY");
            DDL_PERMISSION.DataSource = dt.DefaultView;
            DDL_PERMISSION.DataTextField = "PRI_TEXT";
            DDL_PERMISSION.DataValueField = "ID";
            DDL_PERMISSION.DataBind();
        }
        private int init_value()//通过检测ID是否存在来判断是编辑模式还是修改模式，修改模式则将mode置为1，并完成各个控件数据读取工作
        {
            Bf_Delfile = false;
            if (Request.QueryString["id"] != null)//表示是编辑已有新闻，
            {
                id = Request.QueryString["id"];
                /*mode = Request.QueryString["mode"];*/
                nd = db_news.getDBhandle().GetNewsByID(id);
                TextBox1.Text = nd.news_title;
                CKEditorControl1.Text = nd.news_content;
                //对两个下拉框选中项进行初始化
                DropDownList1.SelectedValue = nd.category_id.ToString();
                DDL_PERMISSION.SelectedValue = nd.news_permission.ToString();
                //好吧，下面这代码怎么看怎么都觉得冗余，或许做成个函数会比较好？不过传参麻烦呀╮(╯▽╰)╭
                if (nd.am_id == -1)//附件不存在
                {
                    P_HasFile.Visible = false;
                    P_NoFile.Visible = true;
                }
                else
                {
                    P_HasFile.Visible = true;
                    P_NoFile.Visible = false;
                    file_path = Server.MapPath("~/") + nd.am_path;
                    HL_File.Text = nd.am_name;
                    attachmentToDel_id = nd.am_id;
                }
                Label_tt.Text = "新闻修改";
                //看懂了吧，其实是控制两块panel的可见与否来解决附件的问题的，虽然很傻，不过看起来还不错~\(≧▽≦)/~
                return 1;
            }
            else//发表新新闻，哎，这个无难度啊无难度
            {
                P_HasFile.Visible = false;
                P_NoFile.Visible = true;
                Label_tt.Text = "发布新闻";
                return 0;
            }
        }
        protected void attach_file(ref news_data news_data_in)
        {
            /*好吧，当我再次看到这段代码的时候，我已经不知道当时我是怎么想的了，不过说起来，附件无法这样几种情况，1.原来有附件然后需要删除
                2.原来没有附件现在添加了附件 3.原来有附件现在更换了附件，恩，就是这样*/
            if (Bf_Delfile == true)//需要进行文件删除
            {
                db_news.getDBhandle().DelAttachmentById(attachmentToDel_id.ToString());
            }
            if (FileUpload1.HasFile)
            {
                System.Random rd = new Random();
                string f_path;
                string f_name = FileUpload1.FileName;
                string [] split_name = f_name.Split(new Char[] {'.'});

                if ((split_name.Length - 1) >= 0)
                {
                    f_path = "News\\ATTACHMENTs\\" + System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_ffff") + "_" + rd.Next(50).ToString() + "." + split_name[split_name.Length - 1];
                }
                else
                {
                    f_path = "News\\ATTACHMENTs\\" + System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_ffff") + "_" + rd.Next(50).ToString();
                }
                FileUpload1.PostedFile.SaveAs(Server.MapPath("\\") + f_path);
                news_data_in.am_id = db_news.getDBhandle().AddAttachment(f_path, f_name);
            }
            else
            {
                news_data_in.am_id = -1;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Convert.ToInt32(Session["Priority"]) < 4) Response.Redirect("..\\");//权限控制……
            if (!Page.IsPostBack)
            {
                Data_Bind();
                mode = init_value();
                //ControlHelper.AddStyleSheet(this.Page, "../CSS/news.css");
                if (mode > 0)
                {
                    release.Text = "修改";
                    this.Title = "编辑内容";
                }
                else
                {
                    this.Title = "发布内容并上传";
                }
            }
        }

        protected void release_Click(object sender, EventArgs e)
        {
            int am_id = -1;
            if (mode == 1)//编辑模式操作
            {
                //nd.news_id = int.Parse(id);

                nd.news_title = TextBox1.Text;
                nd.news_content = CKEditorControl1.Text;
                nd.date = System.DateTime.Now.ToString();
                nd.category_id = int.Parse(DropDownList1.SelectedItem.Value);
                nd.news_permission = int.Parse(DDL_PERMISSION.SelectedItem.Value);
                attach_file(ref nd);
                //nd.am_id = am_id;
                db_news.getDBhandle().UpdateNews(nd);

            }
            else
            {
                news_data nd = new news_data();
                nd.news_title = TextBox1.Text;
                nd.news_content = CKEditorControl1.Text;
                nd.date = System.DateTime.Now.ToString();
                nd.category_id = int.Parse(DropDownList1.SelectedItem.Value);
                nd.news_permission = int.Parse(DDL_PERMISSION.SelectedItem.Value);
                attach_file(ref nd);
                //if (FileUpload1.HasFile)
                //{
                //    file_name = FileUpload1.FileName;
                //    FileUpload1.PostedFile.SaveAs(Server.MapPath("~/") + "News\\ATTACHMENTs\\" + nd.news_title + "_" + file_name);
                //    am_id = db_news.getDBhandle().AddAttachment(Server.MapPath("~/") + "News\\ATTACHMENTs\\" + nd.news_title + "_" + file_name, file_name);
                //}
                //else
                //{
                //    am_id = -1;
                //}
                //nd.am_id = am_id;

                db_news.getDBhandle().AddNews(nd);
            }
            Response.Redirect("news_manager.aspx");
        }

        protected void cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("news_manager.aspx");
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //string nnn = DropDownList1.SelectedValue;
        }

        protected void BtnDeleteFile_Click(object sender, EventArgs e)
        {
            Bf_Delfile = true;
            P_HasFile.Visible = false;
            P_NoFile.Visible = true;
        }

        protected void HL_File_Click(object sender, EventArgs e)
        {
            if (file_path != null)
            {
                start_dl(file_path);
            }
        }
        public void start_dl(string fpath)
        {

            Response.ContentType = "application/x-zip-compressed";
            //Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlPathEncode(fpath));
            Response.AddHeader("Content-Disposition", "attachment;filename=" + nd.am_name);
            Response.TransmitFile(fpath);
        }

        //protected void upload(object sender, EventArgs e)
        //{
        //    if (FileUpload1.HasFile)
        //    {
        //        string file_name = FileUpload1.FileName;
        //        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/") + "\\News\\ATTACHMENTs\\" + file_name);
        //    }
        //}

    }
}
